package com.tedu.charging.service.bill.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tedu.charging.common.pojo.param.ChargingProgressParam;
import com.tedu.charging.common.pojo.param.UserGetBalanceParam;
import com.tedu.charging.service.bill.config.RabbitMQInsideMessageConfig;
import com.tedu.charging.service.bill.feignclient.UserClient;
import com.tedu.charging.common.pojo.web.ServerResult;
import com.tedu.charging.service.bill.elasticsearch.ChargingProgressRepository;
import com.tedu.charging.service.bill.feignclient.CostClient;
import com.tedu.charging.service.bill.feignclient.DeviceClient;
import com.tedu.charging.service.bill.pojo.po.ChargingProgressEsEntity;
import com.tedu.charging.common.pojo.vo.WebsocketMessage;
import com.tedu.charging.common.pojo.vo.ChargingProgressVO;
import com.tedu.charging.service.bill.service.IChargingBillProgressService;
import com.tedu.charging.service.bill.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


/**
 * 充电进度Service业务层处理
 *
 * @author tedu
 * @date 2023-06-15
 */
@Slf4j
@Service
public class ChargingBillProgressServiceImpl implements IChargingBillProgressService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    private ChargingProgressRepository chargingProgressRepository;


    @Autowired
    CostClient costClient;

    @Autowired
    DeviceClient deviceClient;

    @Autowired
    UserClient userClient;

    @Override
    public ChargingProgressVO updateProgress(ChargingProgressParam chargingProgressParam) throws IOException {
       //订单微服务调用计费微服务计算电费
        ChargingProgressVO chargingProgressVO = costClient.computataionCost(chargingProgressParam);


        //判断温度大于45度，推送B级告警，大于48度 ,推送 A级告警
        WebsocketMessage websocketMessage = null;
        if (chargingProgressParam.getTemperature() > 48) {
            //修改前端
            websocketMessage = new WebsocketMessage(chargingProgressParam.getUserId(), 1, "告警信息", "A系统检测到充电异常,设备已被锁定,请拔出充电枪更换设备");
            rabbitTemplate.convertAndSend(RabbitMQInsideMessageConfig.INSIDE_MESSAGE_EXCHANGE, RabbitMQInsideMessageConfig.ALERT_KEY, websocketMessage);
        } else if (chargingProgressParam.getTemperature() > 45) {
            websocketMessage = new WebsocketMessage(chargingProgressParam.getUserId(), 1, "告警信息", "B系统检测到充电异常,你可根据现场情况选择继续充电,或支付订单后更换其他设备");
            rabbitTemplate.convertAndSend(RabbitMQInsideMessageConfig.INSIDE_MESSAGE_EXCHANGE, RabbitMQInsideMessageConfig.ALERT_KEY, websocketMessage);
        }


        //判断电费是否大于余额
        UserGetBalanceParam userGetBalanceParam = new UserGetBalanceParam(chargingProgressParam.getUserId());
        ServerResult<BigDecimal> serverResult = userClient.getBalance(userGetBalanceParam);
        BigDecimal balance = serverResult.getData();
        if (balance.subtract(chargingProgressVO.getTotalCost()).floatValue() <= 0) {
            websocketMessage = new WebsocketMessage(chargingProgressParam.getUserId(), 2, "余额不足", null);
            rabbitTemplate.convertAndSend(RabbitMQInsideMessageConfig.INSIDE_MESSAGE_EXCHANGE, RabbitMQInsideMessageConfig.RECHARGE_KEY, websocketMessage);
        }


        //推送充电进度计算结果到手机端
        websocketMessage = new WebsocketMessage(chargingProgressParam.getUserId(), 3, "进度信息", chargingProgressVO);
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(websocketMessage).toString();
        WebSocketServer.sendInfo(s, chargingProgressParam.getUserId().toString());


//将每次充电进度原始数据保存到elastic Search中
        ChargingProgressEsEntity chargingProgressEsEntity = new ChargingProgressEsEntity();
        BeanUtils.copyProperties(chargingProgressParam, chargingProgressEsEntity);
        chargingProgressEsEntity.setId(System.currentTimeMillis());
        // 创建一个 LocalDateTime 对象
        LocalDateTime dateTime = LocalDateTime.now();
        // 创建一个 DateTimeFormatter 对象，定义日期时间的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 使用 DateTimeFormatter 将 LocalDateTime 转换为字符串
        String dateTimeString = dateTime.format(formatter);
        chargingProgressEsEntity.setCreateTime(dateTimeString);
        chargingProgressRepository.save(chargingProgressEsEntity);
        return chargingProgressVO;
    }

    /**
     * 查询充电进度
     *
     * @param billId
     * @return 充电进度
     */
    @Override
    public ChargingProgressVO selectChargingBillPrgressById(String billId) {

        ChargingProgressVO chargingProgressVO = costClient.getCost(billId);

        return chargingProgressVO;
    }


}
